package com.ccc.dingtalk.listener;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * WebSocket操作类
 */
@Component
@ServerEndpoint(value = "/websocket/{userId}")
public class WebSocket {
    private final static Logger logger = LoggerFactory.getLogger(WebSocket.class);
    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    /**
     * concurrent包的线程安全Map，用来存放每个客户端对应的MyWebSocket对象
     */
    private static ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    private String userId;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.get(userId) == null) {
            //加入map
            webSocketMap.put(userId, this);
            addOnlineCount(); //在线数加1
            logger.info("【WebSocket】-> 客户端【{}】与服务器连接成功！当前在线人数为：{} ", userId, getOnlineCount());
            try {
                sendTip("连接建立成功！");
            } catch (IOException e) {
                logger.error("【WebSocket】-> IO异常", e);
            }
        } else {
            logger.info("【WebSocket】-> 当前客户端【{}】已与服务器连接，请勿重复连接！当前在线人数为：{} ", userId, getOnlineCount());
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        try {
            //从map中删除
            webSocketMap.remove(userId);
            subOnlineCount(); //在线数减1
            session.close();
        } catch (IOException e) {
            logger.error("【WebSocket】-> IO异常", e);
        }
        logger.info("【WebSocket】-> 客户端【{}】关闭连接！当前在线人数还有：{}", userId, getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        if (StrUtil.isNotBlank(message)) {
            if (StrUtil.equals("heartbeat", message)) {
                try {
                    // 向客户端发送心跳
                    sendHeartbeat();
                } catch (IOException e) {
                    logger.error("【WebSocket】-> 向客户端发送心跳发生错误，当前客户端【" + this.userId + "】，错误原因：" + e);
                }
            } else {
                logger.info("【WebSocket】-> 来自客户端【{}】的消息：{}", userId, message);
            }
        }
    }

    /**
     * 发生错误时调用
     *
     * @OnError
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("【WebSocket】-> WebSocket发生错误，当前客户端【" + this.userId + "】，错误原因：" + error);
    }

    /**
     * 向客户端发送心跳
     */
    public void sendHeartbeat() throws IOException {
        Map<String, Object> resultMap = new HashMap<>(1);
        resultMap.put("type", "heartbeat");
        this.session.getBasicRemote().sendText(JSONUtil.toJsonStr(resultMap));
    }

    /**
     * 向客户端发送提示信息
     */
    public void sendTip(String message) throws IOException {
        Map<String, Object> resultMap = new HashMap<>(2);
        resultMap.put("type", "tip");
        resultMap.put("data", message);
        this.session.getBasicRemote().sendText(JSONUtil.toJsonStr(resultMap));
    }

    /**
     * 向客户端发送消息
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 向客户端发送消息（异步发送）
     */
    public void sendAsyncMessage(String message) throws IOException {
        this.session.getAsyncRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendObjectInfo(Object obj) throws IOException {
        Map<String, Object> resultMap = new HashMap<>(2);
        resultMap.put("type", "message");
        resultMap.put("data", obj);
        String jsonStr = JSONUtil.toJsonStr(resultMap);
        for (String item : webSocketMap.keySet()) {
            webSocketMap.get(item).sendMessage(jsonStr);
        }
    }

    public static int getOnlineCount() {
        return onlineCount.get();
    }

    public static void addOnlineCount() {
        onlineCount.incrementAndGet();
    }

    public static void subOnlineCount() {
        if (onlineCount.get() > 0) {
            onlineCount.decrementAndGet();
        }
    }
}
